package com.cqw.commontest.designmode.chainofresponse;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-09-26 16:15
 * @Description:
 */


import lombok.Data;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * 责任链模式：
 */
public class Main {

    public static void main(String[] args) {
        Msg msg = new Msg();
        msg.setMsg("大家好:),<script>,欢迎访问！大家都是996");

        //处理msg
        //new HtmlFilter().doFilter(msg);
        //new SensitiveFilter().doFilter(msg);

//        List<Filter> filters = new ArrayList<>();
//        filters.add(new HtmlFilter());
//        filters.add(new SensitiveFilter());
//
//        for (Filter filter : filters) {
//            filter.doFilter(msg);
//        }


        FilterChain filterChain = new FilterChain();
        filterChain.addFilter(new HtmlFilter())
                .addFilter(new SensitiveFilter());

        FilterChain filterChain1 = new FilterChain();
        filterChain1.addFilter(new FaceFilter());

        filterChain.addFilter(filterChain1);

        filterChain.doFilter(msg);


        System.out.println(msg);


        //封装变化的


    }


}


@Data
@ToString
class Msg {

    private String name;

    private String msg;


}


interface Filter {
    boolean doFilter(Msg msg);
}


class HtmlFilter implements Filter {
    @Override
    public boolean doFilter(Msg msg) {
        String msg1 = msg.getMsg();
        msg1 = msg1.replace('<', '[');
        msg1 = msg1.replace('>', ']');
        msg.setMsg(msg1);
        return true;
    }
}


class SensitiveFilter implements Filter {
    @Override
    public boolean doFilter(Msg msg) {
        String msg1 = msg.getMsg();
        msg1 = msg1.replace("996", "995");
        msg.setMsg(msg1);
        return true;
    }
}


class FaceFilter implements Filter {
    @Override
    public boolean doFilter(Msg msg) {
        String msg1 = msg.getMsg();
        msg1 = msg1.replace(":)", "笑脸");
        msg.setMsg(msg1);
        return true;
    }
}


class FilterChain implements Filter {
    List<Filter> filters = new ArrayList<>();

    public FilterChain addFilter(Filter filter) {
        filters.add(filter);
        return this;
    }

    public void moveFilter(Filter filter) {
        filters.remove(filter);
    }

    public boolean doFilter(Msg msg) {
        for (Filter filter : filters) {
            if (!filter.doFilter(msg)) return false;
        }
        return true;
    }

}





















